const express = require('express');
const app = express();
const cors = require('cors');
const { Server } = require("@hocuspocus/server");
const Y = require('yjs');
const fs = require('fs');
const {History} = require('../model/model.js');
const multer = require('multer');
const axios = require('axios');

// 确保数据目录存在
const dataDir = './data';
if (!fs.existsSync(dataDir)) {
  fs.mkdirSync(dataDir);
}

// 添加 createEmptyDocument 函数定义
const createEmptyDocument = () => {
  const doc = new Y.Doc();
  return doc;
};

// Express 中间件
app.use(cors());
app.use(express.json());

// 配置 Hocuspocus 服务器
const server = Server.configure({
  port: 4333,
  address: 'localhost',
  yDocOptions: { gc: false, gcFilter: () => false },
  onAuthenticate: async (payload) => {
    if (payload.token) {
      if (payload.token === 'readonly') {
        payload.connection.readOnly = true;
      }
      return {
        user: {},
      };
    } else {
      throw new Error('Authentication failed');
    }
  },
  onLoadDocument: async (payload) => {
    const { documentName } = payload;
    const path = `./data/${documentName}.yjs`;

    if (fs.existsSync(path)) {
      const doc = new Y.Doc();
      const docData = fs.readFileSync(path);
      const uint8Array = new Uint8Array(docData);
      Y.applyUpdate(doc, uint8Array);
      return doc;
    } else {
      return createEmptyDocument();
    }
  },
  onStoreDocument: async (payload) => {
    const { documentName, document } = payload;
    const path = `./data/${documentName}.yjs`;
    const update = Y.encodeStateAsUpdate(document);
    fs.writeFileSync(path, update);
  },
});

// 配置图片上传和处理
app.post('/api/process-image', async (req, res) => {
  try {
    // console.log(req.body);
    
    const { imageUrl } = req.body;
    // console.log(imageUrl);
    
    const response = await axios({
      url: imageUrl,
      responseType: 'arraybuffer'
    });  
    // console.log(Buffer.from(response.data).toString('base64'));
    
    res.send({
      success: true,
      data: Buffer.from(response.data).toString('base64')
    });
  } catch (error) {
    res.status(500).send({
      success: false,
      message: '图片处理失败'
    });
  }
});

// API 路由
//保存编辑的记录到数据库
app.post('/add', async(req, res) => { 
  try {
    await History.create(req.body);
    res.send({
      code: 200,
      message: '保存成功'
    });
  } catch (error) {
    console.error('保存失败:', error);
    res.status(500).send({
      code: 500,
      message: '保存失败'
    });
  }
});

//修改记录
app.post('/update', async(req, res) => { 
  try {
    console.log(req.body.currentEditId);
    
    await History.updateMany({ _id: req.body.currentEditId }, req.body);
    res.send({
      code: 200,
      message: '修改成功'
    });
    console.log('修改成功');
    
  } catch (error) {
    console.error('修改失败:', error);
    res.status(500).send({
      code: 500,
      message: '修改失败'
    });
  }
});

//获取所有历史记录
app.get('/getlist', async(req, res) => {  
  const list = await History.find()
  res.send({
    code:200,
    data:list
  })
});

// 启动两个服务器
const startServers = async () => {
  try {
    // 先启动 Hocuspocus
    await server.listen();
    console.log('Hocuspocus server is running on port 4333');
    
    // 然后启动 Express
    app.listen(4334, () => {
      console.log('Express server is running on port 4334');
    });
  } catch (error) {
    console.error('Failed to start servers:', error);
  }
};

// 启动服务器
startServers();

// 不再需要导出 router
module.exports = app;